package com.wooophone.common.email;

import javax.mail.MessagingException;

import org.apache.commons.mail.EmailException;
import org.apache.log4j.Logger;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Template;

public class TemplateEmailService {
	
	private static final Logger log = Logger.getLogger(TemplateEmailService.class);
	
	private FreeMarkerConfigurer freeMarkerConfigurer=null;//FreeMarker的技术类
	
	public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
		this.freeMarkerConfigurer = freeMarkerConfigurer;
	}

	/**
	 * 数据模型
	 * @param model
	 * @return
	 */
	private String getMailText(Object model,String templateName){
		String htmlText="";
		try {
			//通过指定模板名获取FreeMarker模板实例
			Template tpl=freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
			//FreeMarker通过Map传递动态数据
			htmlText=FreeMarkerTemplateUtils.processTemplateIntoString(tpl,model);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return htmlText;
	}
	
	/**
	 * 发送模板邮件
	 * @param model
	 * @param subject
	 * @param target
	 * @param templateFileName
	 * @throws MessagingException
	 * @throws EmailException 
	 */
	public void sendTemplateHtmlMail(Object model,String subject,String target,String templateFileName) throws MessagingException, EmailException{
		String mailContent = getMailText(model,templateFileName);//使用模板生成html邮件内容
		EmailSender.sendHtmlMail(mailContent, subject, target);
		log.debug("发送成功："+target);
	}
	
	/**
	 * 发送模板邮件
	 * @param model
	 * @param subject
	 * @param target
	 * @param templateFileName
	 * @throws MessagingException
	 * @throws EmailException 
	 */
	public void sendTemplateSimpleMail(Object model,String subject,String target,String templateFileName) throws MessagingException, EmailException{
		String mailContent = getMailText(model,templateFileName);//使用模板生成html邮件内容
		EmailSender.sendSimpleMail(mailContent, subject, target);
		log.debug("发送成功："+target);
	}
	
	/**
	 * 
	 * @param content
	 * @param subject
	 * @param target
	 * @throws MessagingException
	 * @throws EmailException 
	 */
	public void sendSimpleMail(String content ,String subject,String target) throws MessagingException, EmailException{
		EmailSender.sendSimpleMail(content, subject, target);
		log.debug("发送成功："+target);
	}
}